import apiConfig from '@/config.js'
const baseUrl = process.env.NODE_ENV === "development" ? apiConfig.dev.baseUrl : apiConfig.prod.baseUrl

const request = (options = {}) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + options.url || '',
            method: options.method || 'GET',
            data: options.data || {},
            header: options.header || {"Content-Type": "application/json", token: uni.getStorageSync('xm-user')?.token}      
        }).then((response) => {
            // 注意：这里使用 response 来接收完整的响应数组
            // 按照 uni.request() 的回调特性，需要分别处理 error 和 res
            const [error, res] = response;
            if (error) {
                reject(error);
                return;
            }
            // 现在 res 是安全的，可以进一步操作
            let { data } = res;
            // 如果从服务端收到的是字符串，尝试解析为JSON
            try {
                if (typeof data === 'string') {
                    data = JSON.parse(data);
                }
            } catch (e) {
                return reject('Response is not valid JSON');
            }
            // 检查 data 是否为 undefined
            if (!data) {
                return reject('No data');
            }
            // 处理具体的业务逻辑，例如检查状态码
            if (data.code === '401') {
                uni.navigateTo({
                    url: '/pages/login/login'
                });
                return;
            }
            resolve(data);
        }).catch((error) => {
            reject(error);
        });
    });
}


const get = (url, data, options = {}) => {
    options.method = 'GET'
    options.data = data
    options.url = url
    return request(options)
}

const post = (url, data, options = {}) => {
    options.method = 'POST'
    options.data = data
    options.url = url
    return request(options)
}

const put = (url, data, options = {}) => {
    options.method = 'PUT'
    options.data = data
    options.url = url
    return request(options)
}

const del = (url, data, options = {}) => {
    options.method = 'DELETE'
    options.data = data
    options.url = url
    return request(options)
}

export default  {
    request,
    get,
    post,
	put,
	del
}